package com.foreknow.service.impl;

import com.foreknow.dao.impl.PersonDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.model.Person;
import com.foreknow.service.PersonService;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class PersonServiceImpl implements PersonService {

    @Override
    public boolean insert(Person person) {
        //连接数据库
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //调用持久层的方法
        PersonDaoImpl dao = new PersonDaoImpl();
        //调用setConnection（）方法注入数据库的连接
        dao.setConnection(conn); //调用的是BaseDao中的setConnection方法
        boolean isRight = false;
        try {
            isRight = dao.insert(person);
            //提交
//            conn.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                //回滚
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

        return isRight;
    }

    public static void main(String[] args) {
        PersonService service = new PersonServiceImpl();
        Person person = new Person();
        person.setName("abc");
        person.setAge(12);
        person.setSchool("fore");
        person.setAddress("shenyang");
        boolean isRight = service.insert(person);
        System.out.println(isRight);
    }

    @Override
    public boolean delete(int id) {
        return false;
    }

    @Override
    public List<Object> queryAll() {
        //连接数据库
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //调用持久层的方法
        PersonDaoImpl dao = new PersonDaoImpl();
        //调用setConnection（）方法注入数据库的连接
        dao.setConnection(conn); //调用的是BaseDao中的setConnection方法
        return dao.queryAll();
    }

    @Override
    public Person queryById(int id) {
        //连接数据库
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        //调用持久层的方法
        PersonDaoImpl dao = new PersonDaoImpl();
        //调用setConnection（）方法注入数据库的连接
        dao.setConnection(conn); //调用的是BaseDao中的setConnection方法
        return dao.queryById(id);
    }

    @Override
    public boolean update(Person person) {
        return false;
    }
}
